package viewcontrollers;

import pojos.Projects;
import viewcontrollers.util.JsfUtil;
import viewcontrollers.util.PaginationHelper;
import beans.ProjectsFacade;
import java.util.List;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.ResourceBundle;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;
import javax.servlet.http.HttpSession;
import pojos.Employees;
import pojos.Expenses;
import pojos.Invoice_Expenses;
import pojos.Invoice_TimeLog;
import pojos.Projects_TimeLog;
import pojos.TimeLog;
import util.CurrentTimeToGMT;

@ManagedBean(name = "projectsController")
@SessionScoped
public class ProjectsController implements Serializable {

    private Projects current;
    private DataModel items = null;
    @EJB
    private beans.ProjectsFacade ejbFacade;
    private PaginationHelper pagination;
    private int selectedItemIndex;
    private String searchKeyword = "";
    private PaginationHelper paginationSearch;
    private DataModel itemsSerch;
    List<Projects_TimeLog> timeLogs = new ArrayList<Projects_TimeLog>();
    private DataModel timeLogSheetData = null;
    private PaginationHelper timeLogSheet;
    String text1;

    public DataModel getItemsSerch() {
        itemsSerch = null;
        if (itemsSerch == null) {
            itemsSerch = getPaginationSearch().createPageDataModel();
        }
        items = itemsSerch;
        return items;
    }

    public PaginationHelper getPaginationSearch() {
        if (paginationSearch == null) {
            paginationSearch = new PaginationHelper(10) {

                @Override
                public int getItemsCount() {
                    return getFacade().count();
                }

                @Override
                public DataModel createPageDataModel() {
                    List list = getFacade().searchKeyWord(searchKeyword);
                    System.out.println(" search Key Word " + searchKeyword);
                    Iterator<Projects> itr = list.iterator();
                    while (itr.hasNext()) {
                        Projects pro = itr.next();
                        System.out.println("project name is from search :" + pro.getProjectName());


                    }
                    return new ListDataModel(list);
                }
            };
        }
        return paginationSearch;
    }

    public String getSearchKeyword() {
        return searchKeyword;
    }

    public void setSearchKeyword(String searchKeyword) {
        this.searchKeyword = searchKeyword;
    }

    public ProjectsController() {
    }

    public Projects getSelected() {
        if (current == null) {
            current = new Projects();
            selectedItemIndex = -1;
        }
        return current;
    }

    private ProjectsFacade getFacade() {
        return ejbFacade;
    }

    public PaginationHelper getPagination() {
        if (pagination == null) {
            pagination = new PaginationHelper(10) {

                @Override
                public int getItemsCount() {
                    return getFacade().count();
                }

                @Override
                public DataModel createPageDataModel() {
                    return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()}));
                }
            };
        }
        return pagination;
    }

    public String prepareList() {
        recreateModel();
        return "List";
    }

    public String prepareView() {
        current = (Projects) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "View";
    }

    public String prepareCreate() {
        current = new Projects();
        selectedItemIndex = -1;
        return "Create";
    }

    public String create() {
        try {
            HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
            String userMail = (String) session.getValue("userName");
            Employees employee = getFacade().searchEmployee(userMail);
            current.setCreatedBy(employee);
            CurrentTimeToGMT gmtTime = new CurrentTimeToGMT();
            current.setCreatedAt(gmtTime.getGMT());
            getFacade().create(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("ProjectsCreated"));
            return prepareCreate();
        } catch (Exception e) {
            e.printStackTrace();
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            e.printStackTrace();
            return null;
        }
    }

    public String prepareEdit() {
        current = (Projects) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "Edit";
    }

    public String update() {
        try {
            HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
            String userMail = (String) session.getValue("userName");
            Employees employee = getFacade().searchEmployee(userMail);
            current.setCreatedBy(employee);
            CurrentTimeToGMT gmtTime = new CurrentTimeToGMT();
            current.setCreatedAt(gmtTime.getGMT());
            getFacade().edit(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("ProjectsUpdated"));
            return "View";
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String destroy() {
        current = (Projects) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        performDestroy();
        recreateModel();
        return "List";
    }

    public String destroyAndView() {
        performDestroy();
        recreateModel();
        updateCurrentItem();
        if (selectedItemIndex >= 0) {
            return "View";
        } else {
            // all items were removed - go back to list
            recreateModel();
            return "List";
        }
    }

    private void performDestroy() {
        try {
            getFacade().remove(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("ProjectsDeleted"));
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
        }
    }

    private void updateCurrentItem() {
        int count = getFacade().count();
        if (selectedItemIndex >= count) {
            // selected index cannot be bigger than number of items:
            selectedItemIndex = count - 1;
            // go to previous page if last page disappeared:
            if (pagination.getPageFirstItem() >= count) {
                pagination.previousPage();
            }
        }
        if (selectedItemIndex >= 0) {
            current = getFacade().findRange(new int[]{selectedItemIndex, selectedItemIndex + 1}).get(0);
        }
    }

    public DataModel getItems() {

        items=null;
        if (items == null) {
            items = getPagination().createPageDataModel();
        }
        return items;
    }

    private void recreateModel() {
        items = null;
        itemsSerch=null;
        timeLogSheetData=null;
    }

    public String next() {
        getPagination().nextPage();
        recreateModel();
        return "List";
    }

    public String previous() {
        getPagination().previousPage();
        recreateModel();
        return "List";
    }

    public SelectItem[] getItemsAvailableSelectMany() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), false);
    }

    public SelectItem[] getItemsAvailableSelectOne() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), true);
    }

    @FacesConverter(forClass = Projects.class)
    public static class ProjectsControllerConverter implements Converter {

        public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
            if (value == null || value.length() == 0) {
                return null;
            }
            ProjectsController controller = (ProjectsController) facesContext.getApplication().getELResolver().
                    getValue(facesContext.getELContext(), null, "projectsController");
            return controller.ejbFacade.find(getKey(value));
        }

        java.lang.Integer getKey(String value) {
            java.lang.Integer key;
            key = Integer.valueOf(value);
            return key;
        }

        String getStringKey(java.lang.Integer value) {
            StringBuffer sb = new StringBuffer();
            sb.append(value);
            return sb.toString();
        }

        public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
            if (object == null) {
                return null;
            }
            if (object instanceof Projects) {
                Projects o = (Projects) object;
                return getStringKey(o.getProId());
            } else {
                throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + ProjectsController.class.getName());
            }
        }
    }

    public String search() {
        return "SearchResult";

    }
    /// TimeLog Sheet

    public PaginationHelper getTimeLogSheet() {
        timeLogSheet = new PaginationHelper(selectedItemIndex) {

            @Override
            public int getItemsCount() {
                return 9;
            }

            @Override
            public DataModel createPageDataModel() {
                List<Projects> allprojects = getFacade().findAll();

                System.out.println(" number of projects " + allprojects.size());

                for (Iterator it = allprojects.iterator(); it.hasNext();) {
                    Projects project = (Projects) it.next();

                    List<TimeLog> list = ejbFacade.getTimeLog(project.getProId());
                    List<Invoice_TimeLog> invoice_list = new ArrayList<Invoice_TimeLog>();
                    for (Iterator<TimeLog> it1 = list.iterator(); it1.hasNext();) {
                        TimeLog timeLog = it1.next();
                        System.out.println(" time log for project " + project.getProId() + "  worked hour : " + timeLog.getWorkedHours());
                        Invoice_TimeLog temp_invoice = new Invoice_TimeLog();

                        // fill shadow been 
                        temp_invoice.setTlId(timeLog.getTlId());
                        temp_invoice.setDate(timeLog.getDate());
                        temp_invoice.setWorkedHours(timeLog.getWorkedHours());
                        temp_invoice.setStatus(timeLog.getStatus());


                        invoice_list.add(temp_invoice);
                    }

                    // 
                    Projects_TimeLog temp_log = new Projects_TimeLog();
                    temp_log.setProjectName(project.getProjectName());
                    temp_log.setTimelogList(invoice_list);
                    timeLogs.add(temp_log);
                }
                return new ListDataModel(timeLogs);
            }
        };

        return timeLogSheet;
    }

    public PaginationHelper getExpensesSheet() {
        timeLogSheet = new PaginationHelper(selectedItemIndex) {

            @Override
            public int getItemsCount() {
                return 9;
            }

            @Override
            public DataModel createPageDataModel() {
                List<Projects> allprojects = getFacade().findAll();

                System.out.println(" number of projects " + allprojects.size());

                for (Iterator it = allprojects.iterator(); it.hasNext();) {
                    Projects project = (Projects) it.next();

                    List<Expenses> list = ejbFacade.getExpenses(project.getProId());
                    List<Invoice_Expenses> invoice_list = new ArrayList<Invoice_Expenses>();
                    for (Iterator<Expenses> it1 = list.iterator(); it1.hasNext();) {
                        Expenses expenses = it1.next();
//                                   System.out.println(" time log for project "+project.getProId()+"  worked hour : "+timeLog.getWorkedHours());
                        Invoice_Expenses temp_invoice = new Invoice_Expenses();

                        // fill shadow been 
                        temp_invoice.setId(expenses.getExpId());
                        temp_invoice.setType(expenses.getExpenseType());
                        temp_invoice.setStatus(expenses.getStatus());
                        temp_invoice.setTask(expenses.getTask());


                        invoice_list.add(temp_invoice);
                    }

                    // 
                    Projects_TimeLog temp_log = new Projects_TimeLog();
                    temp_log.setProjectName(project.getProjectName());
                    temp_log.setInvoice_Expenses(invoice_list);
                    timeLogs.add(temp_log);
                }
                return new ListDataModel(timeLogs);
            }
        };

        return timeLogSheet;
    }

    public DataModel getTimeLogSheetData() {
        timeLogSheetData=null;
        if (timeLogSheetData == null) {
            timeLogSheetData = getTimeLogSheet().createPageDataModel();
            items = timeLogSheetData;
        }
        return items;

    }

    public List<String> complete(String query) {
        System.out.println(" excuting Query " + query);
        List<Projects> list = getFacade().searchKeyWord(query);
        System.out.println(" list size is " + list.size());
        List<String> listDisplayed = new ArrayList<String>();

        for (Iterator it = list.iterator(); it.hasNext();) {
            Projects object = (Projects) it.next();
            listDisplayed.add(object.getProjectName());

        }

        return listDisplayed;
    }

    public void submitinvoice_timeSheet() {
        System.out.println(" in submitting ");
        Iterator<Projects_TimeLog> itr = timeLogSheetData.iterator();
        while (itr.hasNext()) {

            Projects_TimeLog timelog = itr.next();
            List<Invoice_TimeLog> submittedList = timelog.getTimelogList();
            for (Iterator<Invoice_TimeLog> it = submittedList.iterator(); it.hasNext();) {
                Invoice_TimeLog invoice_TimeLog = it.next();
                if (invoice_TimeLog.isIncluded()) {
                    //// logic goes here for what is elected and not selected 
                    System.out.println(" time log id included is " + invoice_TimeLog.getTlId());
                }

            }

        }

    }
}
